#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
调试价格竞争力数据显示问题
"""

import sys
import pandas as pd
import os
from datetime import datetime
sys.path.append('.')

def debug_data_loading():
    """调试数据加载过程"""
    print("=== 调试价格竞争力数据加载 ===")
    
    try:
        from new_app import _load_price_competitiveness_data_cached
        
        print("1. 检查Excel文件路径...")
        current_date_str = str(datetime.now().date())
        excel_path = f'/data_hdd/bryan/bi_strategy_today_iphone_g1/collections/chosen_result_g1_{current_date_str}.xlsx'
        print(f"当前日期: {current_date_str}")
        print(f"Excel文件路径: {excel_path}")
        print(f"文件是否存在: {os.path.exists(excel_path)}")
        
        # 检查目录
        dir_path = os.path.dirname(excel_path)
        print(f"目录路径: {dir_path}")
        print(f"目录是否存在: {os.path.exists(dir_path)}")
        
        if os.path.exists(dir_path):
            files = os.listdir(dir_path)
            print(f"目录中的文件: {files}")
            
            # 查找最近的文件
            excel_files = [f for f in files if f.startswith('chosen_result_g1_') and f.endswith('.xlsx')]
            print(f"找到的Excel文件: {excel_files}")
        
        print("\n2. 尝试加载数据...")
        data = _load_price_competitiveness_data_cached()
        
        print(f"数据加载结果: {data is not None}")
        if data is not None:
            print(f"数据形状: {data.shape}")
            print(f"数据列名: {list(data.columns)}")
            
            if not data.empty:
                print("数据样例:")
                print(data.head())
            else:
                print("数据为空")
        else:
            print("数据为None")
        
        return data
        
    except Exception as e:
        print(f"❌ 调试失败: {e}")
        import traceback
        traceback.print_exc()
        return None

def create_sample_data():
    """创建示例数据用于测试"""
    print("\n=== 创建示例数据 ===")
    
    try:
        # 创建示例价格竞争力数据
        sample_data = pd.DataFrame({
            'product_name': [
                '苹果 iPhone 13', '苹果 iPhone 13', '苹果 iPhone 13',
                '苹果 iPhone 14', '苹果 iPhone 14', '苹果 iPhone 14',
                '苹果 iPhone 15', '苹果 iPhone 15', '苹果 iPhone 15'
            ],
            'target': [0.32, 0.57, 0.84, 0.32, 0.57, 0.84, 0.32, 0.57, 0.84],
            'inquiry_compete_rate': [0.25, 0.45, 0.78, 0.28, 0.52, 0.82, 0.30, 0.55, 0.85],
            'cost_rate_estimated': [0.15, 0.25, 0.35, 0.18, 0.28, 0.38, 0.20, 0.30, 0.40],
            'bi_ratio': [0.85, 0.90, 0.95, 0.88, 0.92, 0.96, 0.90, 0.94, 0.98]
        })
        
        print("示例数据:")
        print(sample_data)
        print()
        
        # 测试HTML生成
        from new_app import AppState
        app_state = AppState()
        
        print("生成HTML表格...")
        html_table = app_state.build_price_email_html(sample_data)
        
        print(f"HTML表格长度: {len(html_table)}")
        print("HTML表格预览（前1000字符）:")
        print(html_table[:1000])
        print("...")
        
        # 保存HTML到文件用于查看
        with open('price_competitiveness_sample.html', 'w', encoding='utf-8') as f:
            f.write(f"""
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="utf-8">
                <title>价格竞争力示例</title>
            </head>
            <body>
                <h2>🍎苹果手机价格竞争力算法（0-95%）</h2>
                {html_table}
            </body>
            </html>
            """)
        
        print("✅ 示例HTML已保存到 price_competitiveness_sample.html")
        
        return sample_data
        
    except Exception as e:
        print(f"❌ 创建示例数据失败: {e}")
        import traceback
        traceback.print_exc()
        return None

def test_display_function():
    """测试显示函数"""
    print("\n=== 测试显示函数 ===")
    
    try:
        from new_app import AppState
        
        app_state = AppState()
        
        # 创建示例数据
        sample_data = pd.DataFrame({
            'product_name': ['苹果 iPhone 13', '苹果 iPhone 14'],
            'target': [0.32, 0.57],
            'inquiry_compete_rate': [0.25, 0.45],
            'cost_rate_estimated': [0.15, 0.25],
            'bi_ratio': [0.85, 0.90]
        })
        
        # 模拟show_tables_data
        app_state.state.show_tables_data = {
            'price_competitiveness': sample_data
        }
        
        print("模拟数据:")
        print(sample_data)
        print()
        
        # 测试显示函数
        print("测试display_price_competitiveness函数...")
        
        # 检查必要的列
        required_cols = ["product_name", "target", "inquiry_compete_rate", "cost_rate_estimated", "bi_ratio"]
        missing_cols = [col for col in required_cols if col not in sample_data.columns]
        
        if missing_cols:
            print(f"❌ 缺少必要列: {missing_cols}")
            return False
        else:
            print("✅ 包含所有必要的列")
        
        # 测试HTML生成
        html_table = app_state.build_price_email_html(sample_data)
        print(f"✅ HTML表格生成成功，长度: {len(html_table)}")
        
        return True
        
    except Exception as e:
        print(f"❌ 测试显示函数失败: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    print("开始调试价格竞争力数据显示问题...")
    
    # 调试数据加载
    data = debug_data_loading()
    
    # 创建示例数据
    sample_data = create_sample_data()
    
    # 测试显示函数
    test_display_function()
    
    print("\n" + "="*50)
    print("调试总结:")
    
    if data is not None and not data.empty:
        print("✅ 数据加载正常")
    else:
        print("❌ 数据加载有问题，可能原因:")
        print("   1. Excel文件不存在")
        print("   2. 文件路径错误")
        print("   3. 文件内容为空")
        print("   4. 数据格式不正确")
    
    if sample_data is not None:
        print("✅ 示例数据创建成功")
        print("✅ HTML表格生成功能正常")
        print("✅ 显示函数测试通过")
    
    print("\n建议:")
    print("1. 检查Excel文件是否存在")
    print("2. 确认文件路径是否正确")
    print("3. 验证文件内容是否包含必要的数据")
    print("4. 如果数据为空，可以使用示例数据进行测试")